import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AppService {
  private readonly logger = new Logger(AppService.name);
  private readonly startTime = Date.now();

  constructor(private readonly configService: ConfigService) {}

  getAppInfo() {
    const uptime = Date.now() - this.startTime;

    return {
      name: 'FaceTime Backend API',
      version: '1.0.0',
      description: '视频通话应用后端服务',
      environment: this.configService.get('app.env', 'development'),
      timestamp: new Date(),
      uptime: this.formatUptime(uptime),
      status: 'running',
      nodeVersion: process.version,
      platform: process.platform,
      arch: process.arch,
      pid: process.pid,
    };
  }

  getVersion() {
    return {
      version: '1.0.0',
      buildTime: new Date(),
      gitCommit: process.env.GIT_COMMIT || 'unknown',
      gitBranch: process.env.GIT_BRANCH || 'unknown',
      nodeVersion: process.version,
      npmVersion: process.env.npm_version || 'unknown',
      environment: this.configService.get('app.env', 'development'),
    };
  }

  ping() {
    const uptime = process.uptime();

    return {
      message: 'pong',
      timestamp: new Date(),
      uptime: Math.floor(uptime * 1000), // 毫秒
      uptimeHuman: this.formatUptime(uptime * 1000),
      status: 'healthy',
      memory: {
        used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
        total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024),
        unit: 'MB',
      },
      cpu: process.cpuUsage(),
      environment: this.configService.get('app.env', 'development'),
      version: '1.0.0',
    };
  }

  // 私有辅助方法
  private formatUptime(milliseconds: number): string {
    const seconds = Math.floor(milliseconds / 1000);
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    const parts = [];
    if (days > 0) parts.push(`${days}d`);
    if (hours > 0) parts.push(`${hours}h`);
    if (minutes > 0) parts.push(`${minutes}m`);
    if (secs > 0) parts.push(`${secs}s`);

    return parts.join(' ') || '0s';
  }
}
